#!/usr/bin/python
from Bio import SeqIO
import hmmtop
import tempfile
import sys

def extract(fastafile,tms):
	
	hmt = hmmtop.tools()
	hmt.add_library('TMX',fastafile)
	hmt.scan_libraries()
	fastas = SeqIO.parse(fastafile,'fasta')
	fastas = SeqIO.to_dict(fastas)
	extracts = [fastas[k] for k,v in hmt.results['TMX'].items() if len(v.keys()) is int(tms)]
	handle=tempfile.NamedTemporaryFile()
	for extract in extracts:
		SeqIO.write(extract,handle,'fasta')
	handle.seek(0)
	return handle
	
if __name__=='__main__':
	import shutil
	handle = extract(sys.argv[1], sys.argv[2])
	shutil.copyfile(handle.name, sys.argv[3])